package com.folderit.apps.rooms;

import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.LoaderManager;
import android.support.v4.content.CursorLoader;
import android.support.v4.content.Loader;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.Toast;

import com.folderit.apps.rooms.data.RoomsContract;
import com.folderit.apps.rooms.data.RoomsContract.ReservationEntry;

import java.util.Calendar;

/**
 * Created by César on 21/12/2014.
 */
public class ReservationsFragment extends Fragment implements LoaderManager.LoaderCallbacks<Cursor> {
    private static final String LOG_TAG = ReservationsFragment.class.getName();
    private ReservationsAdapter mReservationAdapter;

    private ListView mListView;
    private int mSelectedRoomId;
    private int mPosition = ListView.INVALID_POSITION;

    private static final String SELECTED_KEY = "selected_reservation";

    private static final int RESERVATIONS_LOADER = 0;

    // For the reservation view we're showing only a small subset of the stored data.
    // Specify the columns we need.
    private static final String[] RESERVATION_COLUMNS = {
            ReservationEntry.TABLE_NAME + "." + ReservationEntry._ID,
            ReservationEntry.COLUMN_BEGIN,
            ReservationEntry.COLUMN_END,
            ReservationEntry.COLUMN_EVENT_TITLE
    };

    // These indices are tied to RESERVATION_COLUMNS.
    // If RESERVATION_COLUMNS changes, these must change.
    public static final int COL_RESERVATION_ID = 0;
    public static final int COL_RESERVATION_BEGIN = 1;
    public static final int COL_RESERVATION_END = 2;
    public static final int COL_EVENT_TITLE = 3;

    /**
     * A callback interface that all activities containing this fragment must
     * implement. This mechanism allows activities to be notified of item
     * selections.
     */
    public interface ReservationSelectedCallback {
        /**
         * DetailFragmentCallback for when an item has been selected.
         */
        public void onReservationSelected(int reservationId);
    }

    public ReservationsFragment() {
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // Add this line in order for this fragment to handle menu events.
        setRetainInstance(true);

        if (savedInstanceState != null) {
            mSelectedRoomId = savedInstanceState.getInt(ReservationsActivity.SELECTED_ROOM_KEY);
        }

        setHasOptionsMenu(true);
    }

    @Override
    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
        inflater.inflate(R.menu.reservationsfragment, menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();
        if (id == R.id.action_new_reservation) {
            Context context = getActivity();
            CharSequence text = context.getString(R.string.not_available_yet);
            int duration = Toast.LENGTH_SHORT;

            Toast toast = Toast.makeText(context, text, duration);
            toast.show();

            //callCreateReservation();
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        // Get the selected room id from arguments
        Bundle arguments = getArguments();
        if (arguments != null && mSelectedRoomId == 0) {
            mSelectedRoomId = arguments.getInt(ReservationsActivity.SELECTED_ROOM_KEY);
        }

        // The ArrayAdapter will take data from a source and
        // use it to populate the ListView it's attached to.
        mReservationAdapter = new ReservationsAdapter(getActivity(), null, 0);

        View rootView = inflater.inflate(R.layout.fragment_reservations, container, false);

        // Get a reference to the ListView, and attach this adapter to it.
        mListView = (ListView) rootView.findViewById(R.id.listview_reservations);
        mListView.setAdapter(mReservationAdapter);
        mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
                Cursor cursor = mReservationAdapter.getCursor();
                if (cursor != null && cursor.moveToPosition(position)) {
                    ((ReservationSelectedCallback)getActivity())
                            .onReservationSelected(cursor.getInt(COL_RESERVATION_ID));
                }
                mPosition = position;
            }
        });

        // If there's instance state, mine it for useful information.
        // The end-goal here is that the user never knows that turning their device sideways
        // does crazy lifecycle related things.  It should feel like some stuff stretched out,
        // or magically appeared to take advantage of room, but data or place in the app was never
        // actually *lost*.
        if (savedInstanceState != null && savedInstanceState.containsKey(SELECTED_KEY)) {
            // The listview probably hasn't even been populated yet.  Actually perform the
            // swapout in onLoadFinished.
            mPosition = savedInstanceState.getInt(SELECTED_KEY);
        }

        return rootView;
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {

        // Get the selected room id
        if (savedInstanceState != null && mSelectedRoomId == 0) {
            mSelectedRoomId = savedInstanceState.getInt(ReservationsActivity.SELECTED_ROOM_KEY);
        }

        getLoaderManager().initLoader(RESERVATIONS_LOADER, null, this);
        super.onActivityCreated(savedInstanceState);
    }

    private void callCreateReservation() {
        // TODO: This intent could be done in the activity class
        Intent intent = new Intent(getActivity(), CreateEditReservationActivity.class);
        intent.putExtra(CreateEditReservationActivity.SELECTED_ROOM_NEW_RESERVATION_KEY, mSelectedRoomId);

        startActivity(intent);
    }

    @Override
    public void onResume() {
        super.onResume();

        Bundle arguments = getArguments();
        if (arguments != null && arguments.containsKey(ReservationsActivity.SELECTED_ROOM_KEY)) {
            getLoaderManager().restartLoader(RESERVATIONS_LOADER, null, this);
        }
    }

    @Override
    public void onSaveInstanceState(Bundle outState) {
        // Store the selected room
        if (mSelectedRoomId != 0) {
            outState.putInt(ReservationsActivity.SELECTED_ROOM_KEY, mSelectedRoomId);
        }

        // When tablets rotate, the currently selected list item needs to be saved.
        // When no item is selected, mPosition will be set to Listview.INVALID_POSITION,
        // so check for that before storing.
        if (mPosition != ListView.INVALID_POSITION) {
            outState.putInt(SELECTED_KEY, mPosition);
        }

        super.onSaveInstanceState(outState);
    }

    @Override
    public Loader<Cursor> onCreateLoader(int id, Bundle args) {
        // This is called when a new Loader needs to be created.  This
        // fragment only uses one loader, so we don't care about checking the id.

        // Current date and time
        Calendar now = Calendar.getInstance();

        // 10 days after now
        // TODO: Maybe it could be configurable
        Calendar tenDaysAfterNow = Calendar.getInstance();
        tenDaysAfterNow.add(Calendar.DATE, 15);

        String nowStr = RoomsContract.getDbDateTimeString(now.getTime());
        String tenDaysAfterNowStr = RoomsContract.getDbDateTimeString(tenDaysAfterNow.getTime());

        // Show all the reservations for the selected room and for 10 days old (for now)
        Uri reservationsUri =
                ReservationEntry.buildReservationWithRoomAndDateRange(
                        mSelectedRoomId, nowStr, tenDaysAfterNowStr);

        // Sort order:  Ascending, by beginning.
        String sortOrder = ReservationEntry.COLUMN_BEGIN + " ASC";

        // Now create and return a CursorLoader that will take care of
        // creating a Cursor for the data being displayed.
        return new CursorLoader(
                getActivity(),
                reservationsUri,
                RESERVATION_COLUMNS,
                null,
                null,
                sortOrder
        );
    }

    @Override
    public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
        mReservationAdapter.swapCursor(data);
        if (mPosition != ListView.INVALID_POSITION) {
            // If we don't need to restart the loader, and there's a desired position to restore
            // to, do so now.
            mListView.smoothScrollToPosition(mPosition);
        }
    }

    @Override
    public void onLoaderReset(Loader<Cursor> loader) {
        mReservationAdapter.swapCursor(null);
    }
}
